<script setup>
	import {
		computed,
		inject
	} from 'vue';
	import OfflineData from '/common/offline-data-cache.js'
	import {formatNumber} from '/common/numeral.js'
	const responseData = inject('responseData')
	const props = defineProps({
		element: {
			type: Object,
			default: () => {
				return {}
			}
		}
	})
	const styleStr = computed(() => {
		let styleStr = ''
		styleStr += `width:${box.value.w}px;height:${box.value.h}px;`
		styleStr += `left:${box.value.x}px;top:${box.value.y}px;`
		styleStr += `z-index: ${props.element.layer};`
		styleStr += props.element.style
		return styleStr;
	})
	const box = computed(() => {
		try {
			return JSON.parse(props.element.box)
		} catch (e) {
			return {
				w: 100,
				h: 100,
				x: 0,
				y: 0,
			}
		}
	})
	const ruleJson = computed(() => {
		try {
			if (!props.element.ruleJsonStr) {
				return {}
			}
			return JSON.parse(props.element.ruleJsonStr)
		} catch (e) {
			return {}
		}
	})
	const content = computed(() => {
		// 替换实时参数
		let content = props.element.content;
		let defaultContent = ruleJson.value.defaultContent
		if (!content) {
			return defaultContent || ''
		}
		if (!responseData.value || !responseData.value.success) {
			return defaultContent || ''
		}
		// 使用正则找出变量替换的部分
		const reg = new RegExp('(?<=\{{)(.+?)(?=\}})', 'g')
		const array = content.match(reg)
		// 循环每个查出的key，如果匹配上则用对应属性替换，同时应用对应的格式化规则，如果没匹配上则不变
		array.forEach(key=>{
			try{
				const pointer = `{{${key}}}`
				const regExp = new RegExp(pointer, 'g')
				// 获取对应属性的参数
				// 替换每一个出现的key
				const attribute = OfflineData.getAttribute(key);
				let defaultValue = ''
				if(attribute){
					defaultValue = attribute.settingObj.defaultValue
				}else {
					return;
				}
				// 若实时值为空，则使用默认值
				let value = responseData.value[key] == null ? defaultValue:responseData.value[key]
				// 若有格式化，则格式化
				if(attribute.dataType === 'number'){
					value = numberFormat(value, attribute.settingObj)
				}
				content = content.replace(regExp, value)
			}catch(e){
				console.warn(e)
			}
		})
		return content
	})
	
	const numberFormat = (value, settingObj) => {
		value = Number.parseInt(value)
		const pow = settingObj.pow
		if(pow){
			value = value * Math.pow(10, pow)
		}
		const fixed = settingObj.fixed
		if(fixed){
			value = value.toFixed(fixed)
		}
		return value;
	}
</script>

<template>
	<text class="element-image" :style="styleStr">{{content}}</text>
</template>

<style scoped>
	.element-image {
		position: absolute;
		cursor: move;
	}
</style>